package com.party.web.biz.photo;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.party.common.paging.Page;
import com.party.common.utils.StringUtils;
import com.party.core.exception.BusinessException;
import com.party.core.model.member.MemberGroup;
import com.party.core.model.photo.PhotosImgInfo;
import com.party.core.model.photo.PhotosImgInfoWithResource;
import com.party.core.model.photo.PhotosImgTag;
import com.party.core.model.photo.PhotosTag;
import com.party.core.service.cos.CosBizService;
import com.party.core.service.file.IImgResourceService;
import com.party.core.service.photo.IPhotosImgInfoService;
import com.party.core.service.photo.IPhotosImgTagService;
import com.party.core.service.photo.IPhotosTagService;
import com.party.core.service.photo.biz.PhotosCountBizService;
import com.party.web.utils.RealmUtils;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DecimalFormat;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description: 相册分类
 * @Author: yangshoukun
 * @Date: 2018/5/30 14:23
 */
@Service
public class ImgInfoBizService {
    private static Logger logger = LoggerFactory.getLogger(ImgInfoBizService.class);

    @Autowired
    private IPhotosTagService photosTagService;

    @Autowired
    private IPhotosImgTagService photosImgTagService;

    @Autowired
    private IPhotosImgInfoService photosImgInfoService;

    @Autowired
    private PhotosCountBizService photosCountBizService;

    @Autowired
    private IImgResourceService imgResourceService;

    @Autowired
    private CosBizService cosBizService;

    /**
     * 照片列表
     *
     * @param albumId
     * @param page
     * @return
     */
    public List<PhotosImgInfoWithResource> list(String albumId, Page page) {
        if (StringUtils.isEmpty(albumId)) {
            throw new BusinessException("相册分类id不能为空");
        }
        PhotosTag tag = photosTagService.get(albumId);

        PhotosImgInfo photosImgInfo = new PhotosImgInfo();
        if (null != tag && PhotosTag.ALBUM_HOT.equals(tag.getName())) {
            Map<String, Object> params = Maps.newHashMap();
            params.put("hot", true);
            photosImgInfo.setPhotosId(tag.getPhotosId());
            List<PhotosImgInfoWithResource> list = photosImgInfoService.listPageByTag(null, photosImgInfo, params, page);
            int size = 100;
            if (page.getTotalCount() > size) {
                page.setTotalCount(size);
            }
            int temp = (page.getPage() - 1) * page.getLimit() + list.size();
            if (temp > size) {
                list = list.subList(0, list.size() - (temp - size));
            }
            return list;
        }
        return photosImgInfoService.listPageByTag(albumId, photosImgInfo, null, page);
    }

    /**
     * 照片列表--时间线
     *
     * @param albumId
     * @param page
     * @return
     */
    public List<Map<String, Object>> listTimeLine(String albumId, Page page) {
        if (StringUtils.isEmpty(albumId)) {
            throw new BusinessException("相册分类id不能为空");
        }
        PhotosTag tag = photosTagService.get(albumId);
        List<Map<String, String>> timeLine = photosImgInfoService.listTimeLine(tag.getPhotosId(), page);
        if (CollectionUtils.isEmpty(timeLine)) {
            return null;
        }
        List<Map<String, Object>> result = Lists.newArrayList();

        timeLine.forEach(map -> {
            Map<String, Object> reMap = Maps.newHashMap();
            // 处理时间显示
            String takeTime = map.get("take_time");
            String dateStr = takeTime.substring(0, takeTime.length() - 3);
            String blank = " ";
            String hourStr = takeTime.substring(takeTime.length() - 2);
            String minuteStr = ":00";

            String hourStrEnd = new DecimalFormat("00").format(Long.valueOf(hourStr) + 1);

            String showTime = dateStr.concat(blank).concat(hourStr).concat(minuteStr);
            showTime = showTime.concat(" - ").concat(dateStr).concat(blank).concat(hourStrEnd).concat(minuteStr);
            reMap.put("takeTime", showTime);

            List<PhotosImgInfoWithResource> imgs = photosImgInfoService.listTimeLineData(takeTime, tag.getPhotosId(), null, null);
            reMap.put("imgs", imgs);
            result.add(reMap);
        });
        return result;
    }

    /**
     * 删除照片
     *
     * @param tagId:  分类id
     * @param imgIds: 图片id
     */
    @Transactional
    public void delete(String tagId, String imgIds) {
        if (StringUtils.isEmpty(tagId)) {
            throw new BusinessException("相册分类id不能为空");
        }
        PhotosTag photosTag = photosTagService.get(tagId);
        if (PhotosTag.TYPE_SYSTEM.equals(photosTag.getType()) && PhotosTag.ALBUM_HOT.equals(photosTag.getName())) {
            throw new BusinessException("热门中的照片不能编辑");
        }
        if (StringUtils.isEmpty(imgIds)) {
            throw new BusinessException("照片id不能为空");
        }

        if (!PhotosTag.ALBUM_TIME_LINE.equals(photosTag.getName())) {
            // 非时间线, 直接删除关系
            PhotosImgTag param = new PhotosImgTag();
            param.setTagId(tagId);
            param.setImgId(imgIds);
            List<PhotosImgTag> list = photosImgTagService.listFindInSet(param);
            if (CollectionUtils.isNotEmpty(list)) {
                list.forEach(relation -> photosImgTagService.delete(relation.getId()));
            }

            try {
                photosCountBizService.CountImgNum(photosTag.getPhotosId(), new String[] {tagId});
            } catch (Exception e) {
                logger.error("删除照片添加各照片数量冗余数异常", e);
            }
        } else {
            // 时间线
            // 先删除与图片所有的关系
            PhotosImgTag param = new PhotosImgTag();
            param.setImgId(imgIds);
            List<PhotosImgTag> list = photosImgTagService.listFindInSet(param);
            if (CollectionUtils.isNotEmpty(list)) {
                list.forEach(relation -> photosImgTagService.delete(relation.getId()));
            }
            // 再删除图片信息
            String[] imgArray = imgIds.split(",");
            for (String s : imgArray) {
                try {
                    // 可以删除的, 则删掉腾讯云的图片
                    PhotosImgInfo photosImgInfo = photosImgInfoService.get(s);
//                    if (PhotosImgInfo.CAN_DEL.equals(photosImgInfo.getCanDel())) {
                    cosBizService.delImgByCosPath(photosImgInfo.getUrl());
                    imgResourceService.delete(photosImgInfo.getImgResourceId());
//                    }
                } catch (Exception e) {
                    logger.error("从腾讯云删除图片异常", e);
                }
                photosImgInfoService.delete(s);
            }

            try {
                PhotosTag photosTag1 = photosTagService.get(tagId);
                PhotosTag paramTag = new PhotosTag();
                paramTag.setPhotosId(photosTag1.getPhotosId());
                List<PhotosTag> photosTags = photosTagService.list(paramTag);
                List<String> tagIds = photosTags.stream().map(t -> t.getId()).collect(Collectors.toList());
                String[] sArray = new String[tagIds.size()];
                photosCountBizService.CountImgNum(photosTag.getPhotosId(), tagIds.toArray(sArray));
            } catch (Exception e) {
                logger.error("删除照片添加各照片数量冗余数异常", e);
            }
        }
    }

    /**
     * @param photosId
     * @return
     */
    public List<PhotosTag> getTagsByPhotosId(String photosId) {
        if (StringUtils.isEmpty(photosId)) {
            throw new BusinessException("photosId不能为空");
        }
        PhotosTag param = new PhotosTag();
        param.setPhotosId(photosId);
        List<PhotosTag> tags = photosTagService.list(param);

        Iterator<PhotosTag> iterator = tags.iterator();
        while (iterator.hasNext()) {
            PhotosTag tag = iterator.next();
            if (PhotosTag.ALBUM_TIME_LINE.equals(tag.getName()) || PhotosTag.ALBUM_HOT.equals(tag.getName()) || PhotosTag.ALBUM_CHOICENESS.equals(tag.getName())) {
                iterator.remove();
            }
        }
        return tags;
    }

    /**
     * 移动照片到某个相册
     *
     * @param imgIds
     * @param tagIds
     */
    @Transactional
    public void moveImg(String imgIds, String tagIds, String tagId, boolean deleteOld) {
        if (StringUtils.isEmpty(imgIds)) {
            throw new BusinessException("照片id不能为空");
        }
        if (StringUtils.isEmpty(tagIds)) {
            throw new BusinessException("相册id不能为空");
        }

        if (deleteOld) {
            // 先删除以前全部的关系
            PhotosImgTag param = new PhotosImgTag();
            param.setImgId(imgIds);
            param.setTagId(tagId);
            List<PhotosImgTag> list = photosImgTagService.listFindInSet(param);
            if (CollectionUtils.isNotEmpty(list)) {
                list.forEach(relation -> photosImgTagService.delete(relation.getId()));
            }
        }

        String[] tagArray = tagIds.split(",");
        String[] imgArray = imgIds.split(",");
        // 如果不是选择的全部, 就添加新的关系
        if (!"0".equals(tagIds)) {

            MemberGroup member = RealmUtils.getCurrentUser();

            for (int i = 0; i < imgArray.length; i++) {
                String imgId = imgArray[i];
                PhotosImgInfo photosImgInfo = photosImgInfoService.get(imgId);

                for (int j = 0; j < tagArray.length; j++) {
                    String _tagId = tagArray[j];

                    if ("0".equals(_tagId)) {
                        continue;
                    }

                    PhotosImgTag photosImgTag = new PhotosImgTag();
                    photosImgTag.setImgId(imgId);
                    photosImgTag.setTagId(_tagId);
                    photosImgTag.setPhotosId(photosImgInfo.getPhotosId());

                    List<PhotosImgTag> tempList = photosImgTagService.list(photosImgTag);
                    if (CollectionUtils.isEmpty(tempList)) {
                        // 如果精选已经满了500张, 就不能设为精选了
                        PhotosTag photosTag = photosTagService.get(_tagId);
                        if (PhotosTag.ALBUM_CHOICENESS.equals(photosTag.getName())) {
                            Integer count = photosImgInfoService.getCount(photosImgInfo.getPhotosId(), _tagId);
                            if (count >= 500) {
                                throw new BusinessException("精选最多只能设置500张照片");
                            }
                        }
                        photosImgTag.setCreateBy(member.getId());
                        photosImgTag.setUpdateBy(member.getId());

                        photosImgTagService.insert(photosImgTag);
                    }
                }
            }
        }

        try {
            PhotosImgInfo imgInfo = photosImgInfoService.get(imgArray[0]);
            String[] tags = new String[tagArray.length + 1];
            System.arraycopy(tagArray, 0, tags, 0, tagArray.length);
            tags[tags.length - 1] = tagId;
            photosCountBizService.CountImgNum(imgInfo.getPhotosId(), tags);
        } catch (Exception e) {
            logger.error("移动照片添加各照片数量冗余数异常", e);
        }
    }
}
